package com.example.CollaborativeDiscussionLearning.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.CollaborativeDiscussionLearning.config.WenXinConfig;
import com.example.CollaborativeDiscussionLearning.entity.ChatMsg;
import com.example.CollaborativeDiscussionLearning.entity.ChatRoom;
import com.example.CollaborativeDiscussionLearning.entity.ChatUser;
import com.example.CollaborativeDiscussionLearning.entity.Course;
import com.example.CollaborativeDiscussionLearning.service.chatRoomService.ChatRoomService;
import com.example.CollaborativeDiscussionLearning.service.courseService.CourseService;
import com.example.CollaborativeDiscussionLearning.vo.DialogueAnalysisVo;
import com.example.CollaborativeDiscussionLearning.vo.DialogueVo;
import com.example.CollaborativeDiscussionLearning.vo.ResponseDataVO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class WenXinController {

    @Resource
    private WenXinConfig wenXinConfig;

    @Autowired
    private ChatRoomService chatRoomService;

    @Autowired
    private CourseService courseService;

    //历史对话，需要按照user,assistant
    List<Map<String,String>> messages = new ArrayList<>();

    /**
     * 非流式问答
     * @param question 用户的问题
     * @return
     * @throws IOException
     */
    @PostMapping("/WenXin")
    public ResponseDataVO WenXinModel(String question,String roomName) throws IOException {
        if(question == null || question.equals("")){
            return ResponseDataVO.fail("请输入问题");
        }
        log.info("question="+question);
        question=question.replace("@文文","")+"，让我们一步一步思考，如果网上相关文章或者书籍，请给出评价好的三到五个真实的推荐，请分点回答，回答不超过400个字。";
        log.info("question="+question);
        String responseJson = null;
        //先获取令牌然后才能访问api
        log.info("---------------------------"+roomName);
        ChatRoom chatRoom = chatRoomService.queryRoomByRoomName(roomName);
        log.info(chatRoom.toString());
        if (wenXinConfig.flushAccessToken() != null && chatRoom !=null) {
            //传输的数据信息
            HashMap<String, String> user = new HashMap<>();
            //发送的信息
            user.put("role","user");
            user.put("content",question);
            messages.add(user);
            //将信息传换成Json格式
            String requestJson = constructRequestJson(1,0.95,0.8,1.0,false,messages);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestJson);

            Request request = new Request.Builder()
                    .url(wenXinConfig.ERNIE_Bot_4_0_URL + "?access_token=" + wenXinConfig.flushAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            //内容
            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(40, TimeUnit.SECONDS).readTimeout(40,TimeUnit.SECONDS).build();
            try {
                responseJson = HTTP_CLIENT.newCall(request).execute().body().string();
                //将回复的内容转为一个JSONObject
                JSONObject responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                HashMap<String, String> assistant = new HashMap<>();
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                log.info(responseObject.getString("result"));
                String result= responseObject.getString("result");
                result=result.replace("**","");
                //String resultContent = result.substring(result.indexOf("result")+9);
                //log.info(resultContent);
                messages.add(assistant);
                return ResponseDataVO.success(result);
            } catch (IOException e) {
                log.error("网络有问题");
                e.printStackTrace();
                return ResponseDataVO.fail("网络问题，请重试");
            }
        }
        return ResponseDataVO.success("讨论主题不存在或连接失败");
    }

    /**
     * 主题检测
     * */

    @PostMapping("/TopicDetection")
    public ResponseDataVO TopicDetection(String message,String roomName) throws IOException {
        if(message == null || message.equals("")){
            return ResponseDataVO.fail("请输入问题");
        }
        String responseJson = null;
        //先获取令牌然后才能访问api
        log.info("---------------------------"+roomName);
        ChatRoom chatRoom = chatRoomService.queryRoomByRoomName(roomName);
        log.info(chatRoom.toString());
        if (wenXinConfig.flushAccessToken() != null && chatRoom !=null) {
            //传输的数据信息
            HashMap<String, String> user = new HashMap<>();
            String item = "讨论主题是："+chatRoom.getItem()+"讨论内容包括："+chatRoom.getContent();
            //发送的信息
            user.put("role","user");
            //内容
            String promptId="pt-me11awd30tu1kvum";
            Request requestPrompt = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/wenxinworkshop/api/v1/template/info" + "?access_token=" + wenXinConfig.flushAccessToken()+"&id="+promptId+"&item="+item+"&message="+message)
                    .method("GET", null)
                    .addHeader("Content-Type", "application/json")
                    .build();

            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(40, TimeUnit.SECONDS).readTimeout(40,TimeUnit.SECONDS).build();
            try {
                responseJson = HTTP_CLIENT.newCall(requestPrompt).execute().body().string();
                //将回复的内容转为一个JSONObject
                JSONObject responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                HashMap<String, String> assistant = new HashMap<>();
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                String resultPrompt = responseObject.getString("result");
                Integer contentIndex = resultPrompt.indexOf("content");
                Integer templateVariablesIndex = resultPrompt.indexOf("templateVariables");
                String promptContent= resultPrompt.substring(contentIndex+10,templateVariablesIndex-3);
                log.info("promptContent:"+promptContent);
                user.put("content",promptContent);
                messages.add(user);
                //将信息传换成Json格式
                String requestJson = constructRequestJson(1,0.95,0.8,1.0,false,messages);
                RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestJson);

                Request request = new Request.Builder()
                        .url(wenXinConfig.ERNIE_Bot_4_0_URL + "?access_token=" + wenXinConfig.flushAccessToken())
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();

                responseJson = HTTP_CLIENT.newCall(request).execute().body().string();
                //将回复的内容转为一个JSONObject
                responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                log.info(responseObject.getString("result")+"----");

                String result= responseObject.getString("result");

                String resultContent = result.substring(result.indexOf("result")+7);
                if(resultContent.contains("解释:")){
                    resultContent= resultContent.substring(0,resultContent.indexOf("解释:"));
                    resultContent = resultContent.trim();
                }
                log.info(resultContent);
                messages.add(assistant);
                return ResponseDataVO.success(resultContent);

            } catch (IOException e) {
                log.error("网络有问题");
                e.printStackTrace();
                return ResponseDataVO.fail("网络问题，请重试");
            }
        }
        return ResponseDataVO.success("讨论主题不存在或连接失败");
    }

    /**
     * 讨论内容分析
     * */

    @PostMapping("/DialoguesAnalysis")
    public ResponseDataVO DialoguesAnalysis(@RequestParam String roomName) throws IOException {
        String responseJson = null;
        //先获取令牌然后才能访问api
        ChatRoom chatRoom = chatRoomService.queryRoomByRoomName(roomName);
        log.info(chatRoom.toString());
        if (wenXinConfig.flushAccessToken() != null && chatRoom !=null) {
            //获取这个房间的所有对话内容  删除了其中老师和助手的对话
            List<ChatMsg> chatMsgList = handlerChatMsgList(chatRoom);
            if(chatMsgList.isEmpty()){
                return ResponseDataVO.fail("讨论内容为空!");
            }
            //预处理对话
            List<DialogueVo> dialogueVoList = ChatMsgToDialogueVe(chatMsgList);
            if(dialogueVoList.isEmpty()){
                return ResponseDataVO.fail("分析的讨论对话为空");
            }

            // 使用Stream API和Collectors.joining来转换列表并连接字符串
            String concatenatedString = dialogueVoList.stream()
                    .map(msg -> msg.getSender() + ":" + msg.getContent()) // 映射每个对象到 sender:content 格式的字符串
                    .collect(Collectors.joining(" ")); // 使用空格连接字符串
            log.info("multiLineString"+concatenatedString);
            //传输的数据信息
            HashMap<String, String> user = new HashMap<>();
            //发送的信息
            user.put("role","user");
            String item = chatRoom.getItem();
            //内容
            //String promptId="pt-f5vpbc8pahkua2j9";
            String promptId="pt-c1r1k5f8m78gbxae";
            Request requestPrompt = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/wenxinworkshop/api/v1/template/info" + "?access_token=" + wenXinConfig.flushAccessToken()+"&id="+promptId+"&item="+item+"&dialogue="+concatenatedString)
                    .method("GET", null)
                    .addHeader("Content-Type", "application/json")
                    .build();

            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(120, TimeUnit.SECONDS).readTimeout(120,TimeUnit.SECONDS).build();
            try {
                responseJson = HTTP_CLIENT.newCall(requestPrompt).execute().body().string();
                //将回复的内容转为一个JSONObject
                JSONObject responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                HashMap<String, String> assistant = new HashMap<>();
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                String resultPrompt = responseObject.getString("result");
                Integer contentIndex = resultPrompt.indexOf("content");
                Integer templateVariablesIndex = resultPrompt.indexOf("templateVariables");
                String promptContent= resultPrompt.substring(contentIndex+10,templateVariablesIndex-3);
                log.info("promptContent:"+promptContent);
                user.put("content",promptContent);
                messages.add(user);
                //将信息传换成Json格式
                String requestJson = constructRequestJson(1,0.95,0.8,1.0,false,messages);
                RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestJson);

                Request request = new Request.Builder()
                        .url(wenXinConfig.ERNIE_Bot_4_0_URL + "?access_token=" + wenXinConfig.flushAccessToken())
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();

                responseJson = HTTP_CLIENT.newCall(request).execute().body().string();
                //将回复的内容转为一个JSONObject
                responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                String result= responseObject.getString("result");
                //String resultContent = result.substring(result.indexOf("result")+7);
                log.info(result);
                //对结果进行处理
                List<DialogueAnalysisVo> dialogueAnalysisVoList=handlerAnalysisResult(result);
                messages.add(assistant);
                return ResponseDataVO.success(dialogueAnalysisVoList);

            } catch (IOException e) {
                log.error("网络有问题");
                e.printStackTrace();
                return ResponseDataVO.fail("网络问题，请重试");
            }
        }
        return ResponseDataVO.success("讨论主题不存在或连接失败");
    }

    private List<DialogueAnalysisVo> handlerAnalysisResult(String result) {
        String one = "一、主题内容和理解分析";
        String two = "二、讨论观点和立场分析";
        String three ="三、讨论深度和广度分析";
        String four = "四、讨论结果和共识分析";

        Integer oneIndex = result.indexOf(one);
        Integer twoIndex = result.indexOf(two);
        Integer threeIndex = result.indexOf(three);
        Integer fourIndex = result.indexOf(four);

        String res1= result.substring(oneIndex+one.length(),twoIndex);
        String res2= result.substring(twoIndex+two.length(),threeIndex);
        String res3= result.substring(threeIndex+three.length(),fourIndex);
        String res4= result.substring(fourIndex+four.length());
        log.info(res1+"---");
        log.info(res2+"----");
        log.info(res3+"-----");
        log.info(res4+"----");
        List<DialogueAnalysisVo> dialogueAnalysisVoList = new ArrayList<>();
        dialogueAnalysisVoList.add(ToDialogusAnalysis(res1));
        dialogueAnalysisVoList.add(ToDialogusAnalysis(res2));
        dialogueAnalysisVoList.add(ToDialogusAnalysis(res3));
        dialogueAnalysisVoList.add(ToDialogusAnalysis(res4));
        log.info(dialogueAnalysisVoList.toString());
        return dialogueAnalysisVoList;
    }

    public List<ChatMsg> handlerChatMsgList(ChatRoom chatRoom) {
        List<ChatMsg> chatMsgList = chatRoomService.queryAllMsg(chatRoom.getRoomId());
        if(chatMsgList.isEmpty()){
            log.info("chatMsgList为空");
            return chatMsgList;
        }
        Course course = courseService.queryById(chatRoom.getCourseId());
        List<ChatMsg> result = new ArrayList<>();
        for (ChatMsg chatMsg:chatMsgList) {
            if(chatMsg.getSender().equals("2020213710") || chatMsg.getSender().equals(course.getTeacherCode())){
                continue;
            }else{
                if(chatMsg.getMsgType().equals("question")){
                    String content=chatMsg.getContent();
                    Integer index= content.indexOf("@@文文");
                    chatMsg.setContent(content.substring(0,index));
                }
                ChatUser user = chatRoomService.queryUserByCode(chatMsg.getSender());
                chatMsg.setUsername(user.getName());
                result.add(chatMsg);
            }
        }
        log.info(result.toString());
        return result;
    }

    public DialogueAnalysisVo ToDialogusAnalysis(String res){
        String sub1= "分析";
        String sub2="结论";
        String sub3="评分";
        Integer oneIndex = res.indexOf(sub1);
        Integer twoIndex = res.indexOf(sub1);
        Integer threeIndex = res.indexOf(sub1);

        String res1= res.substring(oneIndex+sub1.length(),twoIndex);
        String res2= res.substring(twoIndex+sub2.length(),threeIndex);
        String res3= res.substring(threeIndex+sub3.length());

        DialogueAnalysisVo dialogueAnalysisVo = new DialogueAnalysisVo();
        dialogueAnalysisVo.setAnalysis(res1);
        dialogueAnalysisVo.setAnalysis(res2);
        dialogueAnalysisVo.setAnalysis(res3);

        return dialogueAnalysisVo;
    }

    public List<DialogueVo> ChatMsgToDialogueVe(List<ChatMsg> chatMsgList) {
        List<DialogueVo> dialogueVoList = new ArrayList<>();
        for(ChatMsg chatMsg: chatMsgList){
            DialogueVo dialogueVo=new DialogueVo();
            dialogueVo.setSender(chatMsg.getUsername());
            dialogueVo.setContent(chatMsg.getContent());
            dialogueVoList.add(dialogueVo);
        }
        return dialogueVoList;
    }


    /**
     * 智能问答
     * */
    @PostMapping("/IntelligentAnswer")
    public ResponseDataVO IntelligentAnswer(String message,String roomName) throws IOException {
        if(message == null || message.equals("")){
            return ResponseDataVO.fail("请输入问题");
        }
        log.info("question="+message);
        message=message.replace("@文文","");
        log.info("question="+message);
        String responseJson = null;
        //先获取令牌然后才能访问api
        ChatRoom chatRoom = chatRoomService.queryRoomByRoomName(roomName);
        if (wenXinConfig.flushAccessToken() != null && chatRoom !=null) {
            //传输的数据信息
            HashMap<String, String> user = new HashMap<>();
            String item = "讨论主题是："+chatRoom.getItem()+"讨论内容包括："+chatRoom.getContent();
            //发送的信息
            user.put("role","user");
            //prompt编号
            String promptId="pt-j1z9jtakczbt2hu9";
            Request requestPrompt = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/wenxinworkshop/api/v1/template/info" + "?access_token=" + wenXinConfig.flushAccessToken()+"&id="+promptId+"&question="+message)
                    .method("GET", null)
                    .addHeader("Content-Type", "application/json")
                    .build();

            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).build();
            try {
                responseJson = HTTP_CLIENT.newCall(requestPrompt).execute().body().string();
                //将回复的内容转为一个JSONObject
                JSONObject responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                HashMap<String, String> assistant = new HashMap<>();
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                String resultPrompt = responseObject.getString("result");
                Integer contentIndex = resultPrompt.indexOf("content");
                Integer templateVariablesIndex = resultPrompt.indexOf("templateVariables");
                String promptContent= resultPrompt.substring(contentIndex+10,templateVariablesIndex-3);
                log.info(promptContent);
                user.put("content",promptContent);
                messages.add(user);
                //将信息传换成Json格式
                String requestJson = constructRequestJson(1,0.95,0.8,1.0,false,messages);
                RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestJson);

                Request request = new Request.Builder()
                        .url(wenXinConfig.ERNIE_Bot_4_0_URL + "?access_token=" + wenXinConfig.flushAccessToken())
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();

                responseJson = HTTP_CLIENT.newCall(request).execute().body().string();
                //将回复的内容转为一个JSONObject
                responseObject = JSON.parseObject(responseJson);
                //将回复的内容添加到消息中
                assistant.put("role","assistant");
                assistant.put("content",responseObject.getString("result"));
                log.info(responseObject.getString("result"));
                String result= responseObject.getString("result");
                messages.add(assistant);
                return ResponseDataVO.success(result);

            } catch (IOException e) {
                log.error("网络有问题");
                e.printStackTrace();
                return ResponseDataVO.fail("网络问题，请重试");
            }
        }
        return ResponseDataVO.success("讨论主题不存在或连接失败");
    }

    /**
     * 构造请求的请求参数
     * @param userId
     * @param temperature
     * @param topP
     * @param penaltyScore
     * @param messages
     * @return
     */
    public String constructRequestJson(Integer userId,
                                       Double temperature,
                                       Double topP,
                                       Double penaltyScore,
                                       boolean stream,
                                       List<Map<String, String>> messages) {
        Map<String,Object> request = new HashMap<>();
        request.put("user_id",userId.toString());
        request.put("temperature",temperature);
        request.put("top_p",topP);
        request.put("penalty_score",penaltyScore);
        request.put("stream",stream);
        request.put("messages",messages);
        System.out.println(JSON.toJSONString(request));
        return JSON.toJSONString(request);
    }
}
